package com.puyuba.puyuba.view.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.puyuba.puyuba.R;
import com.puyuba.puyuba.SkinApplication;
import com.pyb.java.basemodule.BaseFragment;
import com.puyuba.puyuba.bean.MsgListBean;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.puyuba.puyuba.network.UserApi;
import com.pyb.java.commonutil.utils.NetUtil;
import com.pyb.java.commonutil.ToastHelper;

import com.puyuba.puyuba.view.adapter.MessageOneAdatper;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import java.util.HashMap;

import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

/**
 * 消息模块第一个fragment 消息页面
 */
public class MessageOneFragment extends BaseFragment {
    private EditText et;
    private TextView tvSearch;
    private SmartRefreshLayout srlMsgOne;
    private RecyclerView rclListone;
    private MessageOneAdatper mAdapter;
    private int localpage = 1;//本地加载的页数
    private int last_page = 1;//最大有几页

    @Override
    public void initView() {

        et = (EditText) getActivity().findViewById(R.id.et_);
        tvSearch = (TextView) getActivity().findViewById(R.id.tv_search_msg1);
        srlMsgOne = (SmartRefreshLayout) getActivity().findViewById(R.id.srl_msg_one);
        rclListone = (RecyclerView) getActivity().findViewById(R.id.rcl_listone);

        rclListone.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new MessageOneAdatper(R.layout.item_message_one);
        mAdapter.bindToRecyclerView(rclListone);

        srlMsgOne.setRefreshHeader(new ClassicsHeader(getContext()));
        srlMsgOne.setRefreshFooter(new ClassicsFooter(getContext()));
        srlMsgOne.setOnRefreshListener(refreshlayout -> {
            boolean mobileConnected = NetUtil.isNetworkAvailable(SkinApplication.sContext);
            if (mobileConnected) {
                getmsglist(0,0,"", CacheUserInfo.getInstance().getId());
            } else {
                ToastHelper.showToast("网络未连接，请检查网络状态");
                if (srlMsgOne!= null){
                    srlMsgOne.finishRefresh();
                }
            }
        });
        srlMsgOne.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                boolean mobileConnected = NetUtil.isNetworkAvailable(SkinApplication.sContext);
                if (mobileConnected) {
                    localpage++;
                    getmsglist(localpage,1,"", CacheUserInfo.getInstance().getId());
                } else {
                    ToastHelper.show("网络未连接，请检查网络状态");
                    if (srlMsgOne!= null){
                        srlMsgOne.finishLoadMore();
                    }
                }
            }
        });

        getmsglist(0,0,"", CacheUserInfo.getInstance().getId());

        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getmsglist(0,0,et.getText().toString().trim(), CacheUserInfo.getInstance().getId());
            }
        });
    }

    //获取消息列表
    public void getmsglist(int page,int type,String keyword,int uid) {
        showLoadingDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("keyword", keyword);
        map.put("type", type);
        map.put("uid", uid);
        map.put("page", page);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);
        RetrofitManger.getInstance().createService(UserApi.class)
                .getmsglist(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<MsgListBean>>applySchedulers())
                .subscribe(new ResponseObserve<MsgListBean>(){

                    @Override
                    public void onSuccess(ResponseEntity<MsgListBean> responseEntity) {

                        if (localpage <= last_page && localpage != 1) {
                            mAdapter.addData(responseEntity.getData().getList());
                        } else {
                            mAdapter.setNewData(responseEntity.getData().getList());
                        }
                        last_page = responseEntity.getData().getPage().getLast_page();
                        if (localpage >= last_page ) {
                            srlMsgOne.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
                        } else {
                            srlMsgOne.finishLoadMore();      //加载完成
                        }
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@NonNull Disposable disposable) { }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        closeLoadingDialog();
                        if (srlMsgOne!= null){
                            srlMsgOne.finishRefresh();
                        }
                    }

                });
    }

    public static MessageOneFragment getInstance(String type) {
        MessageOneFragment messageOneFragment = new MessageOneFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        messageOneFragment.setArguments(args);
        return messageOneFragment;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_message_one;
    }

}
